package com.solution.action;

import java.io.IOException;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.solution.constant.LoginConstants;
import com.solution.delegate.ExaminationServiceDelegate;
import com.solution.exception.DelegateException;
import com.solution.exception.ServiceBeanException;
import com.solution.form.CategoryForm;
import com.solution.model.CategoryType;
import com.solution.model.UserInfo;
import com.solution.util.SearchVO;
import com.solution.webconstant.ExaminationConstant;

public class CategoryAction extends Action{

	/**
	 * logging instance.
	 */
	private Logger logger = Logger.getLogger(CategoryAction.class.getName());

	/**
	 * Default method.
	 */
	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: CategoryAction:execute()");
		CategoryForm categoryForm =(CategoryForm)form;
		request.setAttribute("tab", "CATEGORY");
		request.setAttribute("editLink", "/searchCategory.do?screen_type=Edit");
		request.setAttribute("viewLink", "/searchCategory.do?screen_type=View");
		request.setAttribute("createLink", "/category.do");

		/**
		 * Creation Case.
		 */
		if("/createCategory".equals(mapping.getPath())){
			request.setAttribute("selectedTab", "create");
			return createCategory(mapping, categoryForm, request, response);
		}
		/**
		 * Search Case.
		 */
		else if("/searchCategory".equals(mapping.getPath())){
			if("Edit".equalsIgnoreCase(categoryForm.getScreen_type())){
				request.setAttribute("selectedTab", "edit");
			}else if("View".equalsIgnoreCase(categoryForm.getScreen_type())){
				request.setAttribute("selectedTab", "view");
			}
			return searchCategory(mapping, categoryForm, request, response);
		}
		/**
		 * Updation Case.
		 */
		else if("/updateCategory".equals(mapping.getPath())){
			if("Edit".equalsIgnoreCase(categoryForm.getScreen_type())){
				request.setAttribute("selectedTab", "edit");
			}else if("View".equalsIgnoreCase(categoryForm.getScreen_type())){
				request.setAttribute("selectedTab", "view");
			}
			return updateCategory(mapping, categoryForm, request, response);
		}
		/**
		 * Edit/View Case.
		 */
		else if("/editViewCategory".equals(mapping.getPath())){
			if("Edit".equalsIgnoreCase(categoryForm.getScreen_type())){
				request.setAttribute("selectedTab", "edit");
			}else if("View".equalsIgnoreCase(categoryForm.getScreen_type())){
				request.setAttribute("selectedTab", "view");
			}
			return editViewCategory(mapping, categoryForm, request, response);
		}
		else{
			request.setAttribute("selectedTab", "create");
			return mapping.findForward("init");
		}
	}

	public ActionForward createCategory(ActionMapping mapping,CategoryForm categoryForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: CategoryAction:createCategory()");
		ActionMessages messages = new ActionMessages();
		ActionMessages  errors  = new ActionMessages() ;
		
		CategoryType category=null;
		try{
			// obtain the PO.
			category = convertFormToPersistentObject(categoryForm,request,"add");
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			category = examinationServiceDelegate.createCategory(category);
			if(category != null){
				messages.add("message", new ActionMessage("Category.add.success"));
				saveMessages(request, messages);
				// set the form parameters for the next navigation.
				if(category.getId() != null){
					categoryForm.setCategory_id(category.getId().toString());
				}			
				categoryForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_VIEW);
			}
			else{
				errors.add("error", new ActionMessage("Category.add.fail"));
				categoryForm.setScreen_type("");
			}
		}
		catch(RemoteException re){
			logger.error(re);
			errors.add("error", new ActionMessage("Category.add.fail"));
			categoryForm.setScreen_type("");
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Category.fail.exception", sbe.getMessage()));
			categoryForm.setScreen_type("");
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Category.add.fail"));
			categoryForm.setScreen_type("");
		}
		catch(ParseException pe){
			logger.error(pe);
			errors.add("error", new ActionMessage("Category.add.fail"));
			categoryForm.setScreen_type("");
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: CategoryAction:createCategory()");
		return mapping.findForward("createCategory");
	}

	public ActionForward searchCategory(ActionMapping mapping,CategoryForm categoryForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: CategoryAction:searchCategory()");
		ActionMessages errors  = new ActionMessages();
		try{
			HttpSession session = request.getSession();
			UserInfo userInfo = null;
			if(session != null){
				userInfo = (UserInfo)session.getAttribute(LoginConstants.SESSION_USER_INFO);
			}
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			if(categoryForm.getShow_list() == null || categoryForm.getShow_list().equals("")){
				categoryForm.setShow_list("N");
			}
			else{
				// filling the search criteria.
				SearchVO searchVO = new SearchVO();
				List<CategoryType> categoryList = null;
				if(categoryForm.getCategory_name() != null && !"".equals(categoryForm.getCategory_name().trim())){
					searchVO.addLikeIgnoreCaseCondition("name", categoryForm.getCategory_name().trim());
				}
				if(categoryForm.getCategory_description() != null && !"".equals(categoryForm.getCategory_description().trim())){
					searchVO.addLikeIgnoreCaseCondition("description", categoryForm.getCategory_description().trim());
				}
				if(categoryForm.getCategory_status() != null && !categoryForm.getCategory_status().equals("")){
					searchVO.addEqualsCondition("status", new Short(categoryForm.getCategory_status()));
				}
				searchVO.addEqualsCondition("clientType.id", userInfo.getClientType().getId(), true);
				categoryList = examinationServiceDelegate.getCategories(searchVO);
				categoryForm.setShow_list("Y");
				if(categoryList!=null && categoryList.size()>0){
					categoryForm.setCategory_list(categoryList);
				}
				else{
					errors.add("error", new ActionMessage("Category.search.fail"));
				}
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Category.fail.exception", sbe.getMessage()));
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Category.search.fail"));
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: CategoryAction:searchCategory()");
		return mapping.findForward("searchCategory");
	}

	public ActionForward updateCategory(ActionMapping mapping,CategoryForm categoryForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: CategoryAction:updateCategory()");
		ActionMessages messages = new ActionMessages();
		ActionMessages errors  = new ActionMessages() ;
		CategoryType category =null;
		try{
			category = convertFormToPersistentObject(categoryForm,request,"edit");
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			category = examinationServiceDelegate.modifyCategory(category);
			
			if(category != null){
				messages.add("message", new ActionMessage("Category.update.success"));
				saveMessages(request, messages);
				// set the form parameters for the next navigation.
				if(category.getId() != null){
					categoryForm.setCategory_id(category.getId().longValue()+"");
				}
				categoryForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_VIEW);
			}
			else{
				errors.add("error", new ActionMessage("Category.update.fail"));
				categoryForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
			}
		}
		catch(RemoteException re){
			logger.error(re);
			errors.add("error", new ActionMessage("Category.update.fail"));
			categoryForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Category.fail.exception", sbe.getMessage()));
			categoryForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Category.update.fail"));
			categoryForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		catch(ParseException pe){
			logger.error(pe);
			errors.add("error", new ActionMessage("Category.add.fail"));
			categoryForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: CategoryAction:updateCategory()");
		return mapping.findForward("updateCategory");
	}

	public ActionForward editViewCategory(ActionMapping mapping,CategoryForm categoryForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: CategoryAction:editViewCategory()");
		ActionMessages errors  = new ActionErrors() ;
		try{
			if(categoryForm.getCategory_id() != null && !categoryForm.getCategory_id().equals("")){
				ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
				CategoryType category =examinationServiceDelegate.getCategory(new Long(categoryForm.getCategory_id()));
				//fill the form for displaying the details.
				if(category != null){
					categoryForm.setCategory_name(category.getName());
					if(category.getDescription() != null){
						categoryForm.setCategory_description(category.getDescription());
					}
					if(category.getStatus() != null){
						categoryForm.setCategory_status(category.getStatus().toString());
					}
				}
				else{
					errors.add("error", new ActionMessage("Category.details.fail"));
				}
			}
			else{
				errors.add("error", new ActionMessage("Category.details.fail"));
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Category.fail.exception", sbe.getMessage()));
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Category.details.fail"));
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: CategoryAction:editViewCategory()");
		return mapping.findForward("editViewCategory");
	}
	
	private CategoryType convertFormToPersistentObject(CategoryForm categoryForm,
			HttpServletRequest request,String pageType) throws ServiceBeanException, DelegateException, IOException, ParseException {
		logger.debug("Entering :: CategoryAction:convertFormToPersistentObject()");
		HttpSession session = request.getSession();
		UserInfo userInfo = null;
		if(session != null){
			userInfo = (UserInfo)session.getAttribute(LoginConstants.SESSION_USER_INFO);
		}
		// Creation case.
		CategoryType category = new CategoryType();
		// modification case.
		ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
		if("edit".equalsIgnoreCase(pageType)){
			logger.info("Update case for the category :"+categoryForm.getCategory_id());
			category = examinationServiceDelegate.getCategory(new Long(categoryForm.getCategory_id().trim()));
		}
	    // filling the persistent object.
		if(categoryForm.getCategory_name()!=null && !"".equals(categoryForm.getCategory_name().trim())){
			category.setName(categoryForm.getCategory_name().trim());
		}
		if(categoryForm.getCategory_description() != null && !"".equals(categoryForm.getCategory_description().trim())){
			category.setDescription(categoryForm.getCategory_description().trim());
		}
		if(categoryForm.getCategory_status() != null && !"".equals(categoryForm.getCategory_status().trim())){
			category.setStatus(new Short(categoryForm.getCategory_status().trim()));
		}
	    // creation case.
		if("add".equalsIgnoreCase(pageType)){
			if(userInfo != null){
				category.setCreatedBy(userInfo.getUsername());
			}
			category.setCreatedOn(new Date());
			category.setClientType(userInfo.getClientType());
		}
		// modification case.
		else{
			if(userInfo != null){
				category.setModifiedBy(userInfo.getUsername());
			}
			category.setModifiedOn(new Date());
		}
		logger.debug("Exiting :: CategoryAction:convertFormToPersistentObject()");
		return category;
	}
}
